package com.bridgeintelligent.tag.engine.parse;

import com.bridgeintelligent.tag.engine.api.BaseCode;
import com.bridgeintelligent.tag.engine.api.DimInfo;
import com.bridgeintelligent.tag.engine.api.DimItemInfo;
import com.bridgeintelligent.tag.engine.api.rsp.CustomerGroupRsp;
import com.bridgeintelligent.tag.engine.core.cache.CacheConfig;
import com.bridgeintelligent.tag.engine.core.cache.CacheUtils;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms.Bucket;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * Created by JackCheung on 2019/10/21 4:01 PM.
 */
@Slf4j
public class CustomerGroupParse {

    private static final String GROUP_FORMAT = "%s_%s";
    private static final String showTypeFormat = "%s:%s";
    private static final String showNameAndValue = "02";
    private static final String showNameAndValue2 = "+标签值";

    /**
     * 构建返回数据CustomerGroupRsp
     *
     * @param searchResponse
     * @param fields
     * @return
     */
    public static CustomerGroupRsp create(SearchResponse searchResponse, List<String> fields) {
        CustomerGroupRsp customerGroupRsp = new CustomerGroupRsp();
        CustomerGroupRsp.DataRsp dataRsp = new CustomerGroupRsp.DataRsp();
        dataRsp.setTotalCount(searchResponse
                .getHits()
                .getTotalHits().value);
        customerGroupRsp.setCode(BaseCode.SUCCESS);
        Aggregations aggregations = searchResponse.getAggregations();
        //返回处理后的数据
        return parseHandler(aggregations, customerGroupRsp, fields, dataRsp);
    }

    /**
     * 解析数据，从缓存中取出对应值
     *
     * @param aggregations
     * @param customerGroupRsp
     * @param fields
     * @param dataRsp
     * @return
     */
    private static CustomerGroupRsp parseHandler(Aggregations aggregations, CustomerGroupRsp customerGroupRsp, List<String> fields, CustomerGroupRsp.DataRsp dataRsp) {
        Map<String, Long> result = new HashMap<>(fields.size());
        fields.forEach(s -> {
            Terms byAgeAggregation = aggregations.get(s);
            for (Bucket buck : byAgeAggregation.getBuckets()) {
                //从缓存中获取dimName
                String dimName = Optional
                        .ofNullable((DimInfo) CacheUtils.getCacheInfo(CacheConfig.DIM_INFO, s))
                        .map(DimInfo::getDimName)
                        .orElse(s);
                //从缓存中获取itemName
                String itemName = Optional
                        .ofNullable((DimItemInfo) CacheUtils.getCacheInfo(CacheConfig.DIM_ITEM_INFO, String.format(GROUP_FORMAT, s, buck.getKey())))
                        .map(DimItemInfo::getDimItemName)
                        .orElse(buck.getKey().toString());
                //从缓存中获取showType
                String showType = Optional
                        .ofNullable((DimInfo) CacheUtils.getCacheInfo(CacheConfig.DIM_INFO, s))
                        .map(DimInfo::getDimeShowType)
                        .orElse("03");//如果为空则showType为03
                //根据不同类型返回不同展示结果
                if (showType.equals(showNameAndValue) || showType.contains(showNameAndValue2)) {
                    result.put(String.format(showTypeFormat, dimName, itemName), buck.getDocCount());
                } else {
                    result.put(itemName, buck.getDocCount());
                }
            }
        });
        dataRsp.setMaxMap(result);
        customerGroupRsp.setData(dataRsp);
        return customerGroupRsp;
    }
}
